<template>
  <div class="charts"
    style="color: #000; width: 100%; height: 100%;">
    <div ref="singleBar"
      :style="[ { height: `${cHeight}px`, width: '100%' } ]"></div>
  </div>
</template>
<script>
// 分配饼图:参考地址 http://gallery.echartsjs.com/editor.html?c=xBJ06lIMUQ
// const echarts = resolve => require(['echarts'], resolve) // 请使用懒加载
import echarts from 'echarts'
import { on, off, toThousandFilter } from '@/utils/util';
export default {
  data () {
    return {
      myChart: null
    };
  },
  props: {
    xData: {
      type: Array,
      default: function () {
        return [];
      }
    },
    yData: {
      type: Array,
      default: function () {
        return [];
      }
    },
    cHeight: {
      type: [String, Number],
      default: 200
    },
    // 图表标题
    chartTitle: {
      type: String,
      default: ''
    },
    // 柱状图宽度
    barWidth: {
      type: String,
      default: '60%'
    },
    // x轴刻度字体大小
    xLabelSize: {
      type: String,
      default: '12'
    },
    axisLabelFormatter: { // x轴数据的自定义格式
      type: String,
      default: '{value}'
    },
    // 提示弹窗的formatter
    tooltipFormatter: {
      type: String,
      default: null
    },
    // y轴刻度字体大小
    yLabelSize: {
      type: String,
      default: '12'
    },
    seriesData: {
      type: Array,
      default: function () {
        return [];
      }
    },
    // 是否自定义tooltip
    isDefineTooltip: {
      type: Boolean,
      default: false
    },
    // 自定义的tooltip对象
    defineTooltip: {
      type: Object,
      default: function () {
        return {};
      }
    },
    // 柱状图柱子颜色
    chartColor: {
      type: Array,
      default: function () {
        return ['#0067e1', '#75beff', '#23cbab', '#fed500'];
      }
    },
    // 柱子背景颜色
    backgrounColor: {
      type: Array,
      default: function () {
        return ['rgba(31,121,255,0.05)']
      }
    },
    // 是否显示柱子上面的数字
    showTopData: {
      type: Boolean,
      default: false
    },
    //是否是多个柱子
    multipColumn: {
      type: Boolean,
      default: false
    },
    isShowLegend: {
      type: Boolean,
      default: true
    },
    // 是否显示y轴轴线
    isShowYAxisLine: {
      type: Boolean,
      default: true
    },
    dataZoom: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  watch: {
    seriesData () {
      this.againCanvas();
    }
  },
  computed: {
    p_seriesData () {
      let max = Math.max.apply(null, this.seriesData);
      return new Array(this.seriesData.length).fill(max);
    },
    option () {
      let seriesArr = []
      let seriesItem = {
        name: '数量',
        // type决定图表类型
        type: 'bar',
        z: 2,
        barGap: 0,
        data: [],
        barWidth: this.barWidth,
        animationDuration: 1500,
        itemStyle: {
          normal: {
            label: {
              show: this.showTopData, // 开启显示
              position: 'top', // 在上方显示
              textStyle: { // 数值样式
                color: '#282828',
                fontSize: 12
              },
              formatter: (value) => {
                return toThousandFilter(value.value) // 数字格式化
              }
            }
          }
        }
      }
      // if (this.multipColumn) {
      this.seriesData.forEach((e, idx) => {
        let item = JSON.parse(JSON.stringify(seriesItem))
        item.name = e.name || ''
        item.type = e.type || item.type
        item.z = e.z || item.z
        item.data = e.data
        item.barWidth = e.barWidth || item.barWidth
        item.animationDuration = e.animationDuration || item.animationDuration
        item.itemStyle.normal.color = this.chartColor[(idx) % this.chartColor.length]
        seriesArr.push(item)
      })
      // } else {
      //   seriesItem.data = this.seriesData
      //   seriesArr = [seriesItem]
      // }
      return {
        color: this.chartColor,
        title: {
          text: this.chartTitle,
          subtext: '',
          textStyle: {
            color: '#464646',
            fontSize: 16
          }
        },
        tooltip: this.isDefineTooltip ? this.defineTooltip : {
          // trigger(触发类型)，可选'item','axis','none'
          trigger: 'axis',
          axisPointer: {
            // 指示器类型,可选'line','shadow','cross'
            type: 'shadow'
          },
          formatter: this.tooltipFormatter,
          textStyle: {
            align: 'left'
          }
        },
        legend: {
          show: this.isShowLegend,
          top: '3%',
          left: 'center',
        },
        grid: {
          top: '10%',
          right: '3%',
          bottom: '3%',
          left: '3%',
          containLabel: true
        },
        dataZoom: this.dataZoom,
        xAxis: [
          {
            type: this.yData.length > 0 ? 'value' : 'category',
            // axisTick 坐标轴刻度相关设置
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            // axixLine 坐标轴轴线相关设置
            axisLine: {
              show: true,
              lineStyle: {
                color: '#F2F4F6'
              }
            },
            // axisLabel 坐标轴刻度标签的相关设置
            axisLabel: {
              // show: true,
              color: '#B6BFCE',
              fontSize: this.xLabelSize,
              formatter: this.axisLabelFormatter
            },
            data: this.xData,
          }
        ],
        yAxis: [{
          type: this.yData.length > 0 ? 'category' : 'value',
          axisLabel: {
            show: true,
            color: '#B6BFCE',
            fontSize: this.yLabelSize
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
              color: '#F2F4F6'
            }
          },
          axisLine: {
            show: this.isShowYAxisLine,
            lineStyle: {
              color: '#F2F4F6'
            }
          },
          axisTick: {
            show: false,
            lineStyle: {
              color: 'rgba(12, 156, 240, 0.2)'
            }
          },
          data: this.yData,
        }],
        series: seriesArr
      }
    }
  },
  methods: {
    // 重新画图
    againCanvas () {
      this.myChart.setOption(this.option, true);
      this.myChart.resize();
    }
  },
  mounted () {
    this.myChart = echarts.init(this.$refs['singleBar']);
    this.myChart.setOption(this.option);
    // 数量柱状图点击事件
    this.myChart.getZr().on('click', params => {
      let pointInPixel = [params.offsetX, params.offsetY]
      if (this.myChart.containPixel('grid', pointInPixel)) {
        let xIndex = this.myChart.convertFromPixel({ seriesIndex: 0 }, [params.offsetX, params.offsetY])[0]
        let options = this.myChart.getOption()
        this.$emit('barClickFn', xIndex, options, params)
      }
    });
    window.addEventListener('resize', this.againCanvas)
  },
  destroyed () {
    window.removeEventListener('resize', this.againCanvas)
  }
}
</script>
